define(function(require){
    $(function(){
    	/*---------- 素材管理——管理员 ----------*/
    	
    	/* 素材数据-Table */
    	var bodyTemplate = ['<tr material_id="{id}">',
    	                    	'<td class="txtc">{id}</td>',
	    	                    '<td class="txtc">{name}</td>',
	    	                    '<td class="txtc">{uploader}</td>',
	    	                    '<td class="txtc">{upload_time}</td>',
	    	                    '<td class="txtc">{width}</td>',
	    	                    '<td class="txtc">{height}</td>',
	    	                    '<td class="txtc">{type}</td>',
	    	                    '<td class="txtr" style="padding-right:20px;">@modifySizeToKB({size})kb</td>',
	    	                    '<td class="txtc"><a href="{landingpage}" target="_blank">{landingpage}</a></td>',
	    	                    '<td class="txtc">{frequency}</td>',
	    	                    '<td class="txtc">{status}<input type="hidden" name="reason" value="{reason}"></td>',
    	                     	'<td class="txtc">',
    	                     		'<a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a>',
    	                     		'<a class="ibtn acceptbtn" href="javascript:;" title="通过"><span class="glyphicon glyphicon-thumbs-up"></span></a>',
    	                     		'<a class="ibtn refusebtn" href="javascript:;" title="拒绝"><span class="glyphicon glyphicon-thumbs-down"></span></a>',
	                     		'</td>',
    	                     '</tr>'].join('');
    	
    	var grid = Grid.init({
            holder:'materialList',
            bodyTemplate:bodyTemplate,
            dataSource:'/trp/material/get_materials/',
            pageTemplate:semi.grid.pageTemplate,
            sendOnPageSize: true
    	 });
    	
    	window.modifySizeToKB=function(size){
    		if(size){
    			size = size *1.0/1024;
    			return size.toFixed(2);
    		}
    		return size;
    		
    	};
    	//数据重置：审核状态   0待审核    1通过    2拒绝
    	grid.modifyModel(function(data){
        	if(data.status==0){
        		data.status = '<span class="label label-default" style="font-size:14px;">待审核</span>';
        	}else if(data.status==1){
        		data.status = '<span class="label label-success" style="font-size:14px;">通过</span>';
        	}else{
        		data.status = '<span class="label label-danger showreason" style="font-size:14px;cursor:pointer;">拒绝</span>';
        	}
        	data.landingpage = data.landingpage.toUrl();
    	});
    	grid.onfilled(function(data){
     		grid.data = data;
     		$('.ibtn').tooltip();
     	});
    	
    	//数据搜索
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
        		status = $('.pageheader select[name=status]').val(),
        		size = $('.pageheader [name=measure]').val(),
        		type = $('.pageheader [name=type]').val(),
        		width = '', height = '',
            	pageSize = 20;
        	
        	if(size!=-1){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
        		search_text: txt,
        		status: status,
        		type: type,
        		width: width,
	        	height: height,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();

        //按尺寸搜索
        $('.pageheader [name=measure]').select2({
        	ajax: {
        		url: '/trp/material/get_material_size/',
        		results: function(data){
        			var resultArr = [{id:'', text:'全部尺寸'}];
        			$.each(data.data, function(i,n){
        				var val = n.width+'x'+n.height;
        				resultArr.push({id:val, text:val});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
        //按类型搜索
        $('.pageheader [name=type]').select2({
        	ajax: {
        		url: '/trp/material/get_material_type/',
        		results: function(data){
        			var resultArr = [{id:'', text:'全部类型'}];
        			$.each(data.data, function(i,n){
        				resultArr.push({id:n.id, text:n.name});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
        
        //按审核状态搜索
        $('.pageheader select[name=status]').on('change', function(){
        	filterData();
        }).select2();
        
        //按ID、名称和上传者模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        var updateMaterial = function(json, callback){
    		$ajax.ajax({
    			url : '/trp/material/do_audit/',
        		data: JSON.stringify(json),
        		contentType : "application/json",
                type : 'POST',
                dataType : 'json',
                success: function(data){
                	if(json.status==1){
                		$dialog.alert('素材审核成功！','success');
                	}else if(json.status==2){
                		$dialog.alert('素材审核成功！','success');
                	}
                	if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this, data);
            		filterData(semi.utils.gridPage(grid));
                },
                error: function(data){
                	$dialog.alert('素材审核失败，请稍后重试！','warning');
                }
        	 });
    	}
        
        //status 1，通过，2拒绝
        require('validate');
        /*var refuseDialog = function(data, callback){
        	return $dialog({
        		id: 'refuseDialog',
                title: '素材审核',
                content: $('.pop-refuse').clone().show()[0],
                width: '500px',
                button: [{
                	value: '确定',
                	callback: function(){
                		var $d = this, $node = $(this.node);
                		if(!$('form',$node).valid())return false;
                		updateMaterial($.extend(data,{
                			status: 2,
                			reason: $('[name=reason]',$node).val()
                		}), function(){
                			$d.close().remove();
                			if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this, data);
                		});
                    	return false;
                    },
                    autofocus: true
                },{
                	value: '取消'
                }]
            });
        }*/
        
        /* 预览-dialog */
        require('./common/popmaterial').init();
        
        /* 通过+拒绝-dialog */
        $(document).on('click', '.acceptbtn,.refusebtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), material_id = $tr.attr('material_id'),data = {material_id:material_id}
        	
        	//通过
        	if($this.hasClass('acceptbtn')){
        		updateMaterial($.extend(data,{status:1}));
        		return;
        	}
        	//拒绝
        	$dialog({
                title: '素材审核',
                content: $('.pop-refuse').clone().show()[0],
                width: '500px',
                okValue: '确定',
                ok: function(){
            		var $d = this, $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		updateMaterial($.extend(data,{
            			status: 2,
            			reason: $('[name=reason]',$node).val()
            		}), function(){
            			$d.close().remove();
            		});
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        });
        
        /* 查看拒绝原因-dialog */
        $(document).on('click', '.showreason', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), reason = $('[name=reason]',$tr).val();
        	$dialog({
                title: '查看拒绝原因',
                content: $('.pop-refuse').clone().show()[0],
                width: '500px',
                onshow: function(){
                	var $node = $(this.node);
                	if(semi.utils.isEmpty(reason))reason = ' ';
                	$('[name=reason]',$node).val(reason).attr('readonly','readonly');
                },
                cancelValue: '关闭',
                cancel: true
            }).showModal();
        });
    });
});